<template>
  <!-- echarts 渲染核心组件 -->
  <div :class="`echarts-container-${privateKey}`"></div>
</template>
<script lang="ts" setup>
import * as echartCore from "echarts/core";
import { BarChart, LineChart, PieChart, RadarChart } from "echarts/charts";
import {
  TitleComponent,
  LegendComponent,
  GridComponent,
  TooltipComponent,
  ToolboxComponent,
  DataZoomComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { onBeforeUnmount, onMounted, reactive, watch } from "vue";
interface Emits {
  (t: "rendered"): void;
  (t: "click", e: any): void;
  (t: "rendered"): void;
}
interface Props {
  privateKey?: string;
  echartsConfig?: any;
  echartChartsList?: any[];
}
const getBaseConfig = () => ({});

const emit = defineEmits<Emits>();

const props = withDefaults(defineProps<Props>(), {
    privateKey: "privateKey",
    echartsConfig: () => ({}),
    echartChartsList: () => [RadarChart, PieChart, LineChart, BarChart],
  }),
  instances = {
    echartInstance: null,
    sizeObsever: null,
  };
watch(
  () => props.echartsConfig,
  (nv) => {
    if (instances.echartInstance) {
      instances.echartInstance.hideLoading();
      const finalConfig = Object.assign(getBaseConfig(), nv);
      instances.echartInstance.setOption(finalConfig);
    }
  },
  {
    deep: true,
  }
);
echartCore.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent,
  LabelLayout,
  UniversalTransition,
  ...props.echartChartsList,
  CanvasRenderer,
]);

onMounted(() => {
  const echartInstance = echartCore.init(
    document.querySelector(`.echarts-container-${props.privateKey}`)
  );
  echartInstance.setOption(Object.assign(getBaseConfig(), props.echartsConfig));
  instances.echartInstance = echartInstance;
  echartInstance.on("click", (e) => {
    emit("click", e);
  });
  echartInstance.on("rendered", () => {
    emit("rendered");
  });
  // 显示加载动画
  echartInstance.showLoading();
  // 监听容器大小变化,如果变化,促使echarts重新渲染
  const resizeObsever = new ResizeObserver(() => {
    echartInstance.resize();
  });
  resizeObsever.observe(
    document.querySelector(`.echarts-container-${props.privateKey}`)
  );
  instances.sizeObsever = resizeObsever;
});
onBeforeUnmount(() => {
  // 清除容器的大小变化监听
  if (instances.sizeObsever) {
    instances.sizeObsever.disconnect();
  }
  // 将echarts实例销毁
  if (instances.echartInstance && !instances.echartInstance.isDisposed()) {
    instances.echartInstance.dispose();
  }
  instances.sizeObsever = null;
  instances.echartInstance = null;
});
</script>

<style>
[class^="echarts-container"] {
  width: 100%;
  overflow: hidden;
}
</style>
